<?php
namespace app\admin\controller;
use app\common\model\School as SchoolModel;
use app\common\service\CateService;
use app\admin\model\Cate as CateModel;
use think\facade\Request;
use think\validate;
use think\Db;
use PHPExcel\PHPExcel;
use library\ArrayOperate;
use app\common\model\SchoolTest;

class School extends Base
{
    
    public function index(){
		
		$data['kw'] = input('kw');
		$data['Nowpage'] = input('get.page') ? input('get.page'):1;
		
		$map['status'] = 1;
		if($data['kw']&&$data['kw']!==""){
			$map['college_name'] = ['like',"%" . $data['kw'] . "%"];
		}
		$list = SchoolModel::where($map)->order('id asc')->paginate(config('list_rows'))->toArray();
		$data['count'] = $list['total'];
		$data['allpage'] = $list['last_page'];  
		$user_date = $list['data'];
		//dump($data['kw']);
		if(input('get.page')){
			return json($user_date);
		}
		$this->assign($data);
		return $this->fetch();
    }
	
	public function get_area_child(){
		$id = $this->request->get('id',0);
		$act = $this->request->get('act',0);
		$list = Db::name('area')->where('level',$act)->where('pid',$id)->field('id,name')->select();
		$html = '<option value="">==请选择==</option>';
		foreach($list as $val){
			$html .= '<option value="'.$val['id'].'">'.$val['name'].'</option>';
		}
		return $html;
	}
    public function edit(){
       if ($this->request->isPost()) {
            $data = $this->request->post();//dump($data);die;
			$validate = validate('School');
			if (!$validate->check($data)) {
				$this->error($validate->getError());
			}
			//dump($data);die;
			Db::startTrans();
			if(!empty($data['syiliu'])){
				$data['syiliu'] = json_encode(array_values($data['syiliu']),JSON_UNESCAPED_UNICODE);
			}
			if(!empty($data['pinggu'])){
				$data['pinggu'] = json_encode(array_values($data['pinggu']),JSON_UNESCAPED_UNICODE);
			}
			if(!empty($data['tese_major'])){
				$data['tese_major'] = json_encode(array_values($data['tese_major']),JSON_UNESCAPED_UNICODE);
			}
			
			if ($data['id']) {//编辑
                //$res = SchoolModel::update($data, ['id' => $data['id']]);
				$obj = new SchoolModel;
				$res =$obj->allowField(true)->save($data,['id' => $data['id']]);
                if ($res) {
					Db::name('school_tese_data')->where('school_id',$data['id'])->delete();
					if(!empty($data['school_tese'])){
						$school_tese = array_filter(explode(',',$data['school_tese']));
						$dataTs = [];
						foreach ($school_tese as $val) {
							 $dataTs[] = ['tese_id' => $val, 'school_id' => $data['id']];
						}
						Db::name('school_tese_data')->insertAll($dataTs);
					}
					/*Db::name('school_type_data')->where('school_id',$data['id'])->delete();
					if(!empty($data['school_type'])){
						$school_type = array_filter(explode(',',$data['school_type']));
						$dataTy = [];
						foreach ($school_type as $val) {
							 $dataTy[] = ['type_id' => $val, 'school_id' => $data['id']];
						}
						Db::name('school_type_data')->insertAll($dataTy);
					}
					Db::name('school_xingzhi_data')->where('school_id',$data['id'])->delete();
					if(!empty($data['school_xingzhi'])){
						$school_xingzhi = array_filter(explode(',',$data['school_xingzhi']));
						$dataXz = [];
						foreach ($school_xingzhi as $val) {
							 $dataXz[] = ['xingzhi_id' => $val, 'school_id' => $data['id']];
						}
						Db::name('school_xingzhi_data')->insertAll($dataXz);
					}*/	
					Db::commit();
                    $this->success('编辑成功');
                } else {
					Db::rollback();
                    $this->error('编辑失败');
                }
            } else {//添加
                $obj = new SchoolModel;
                $res = $obj->allowField(true)->save($data);
                if ($res) {
					if(!empty($data['school_tese'])){
						$school_tese = array_filter(explode(',',$data['school_tese']));
						$dataTs = [];
						foreach ($school_tese as $val) {
							 $dataTs[] = ['tese_id' => $val, 'school_id' => $obj->id];
						}
						Db::name('school_tese_data')->insertAll($dataTs);
					}
					/*if(!empty($data['school_type'])){
						$school_type = array_filter(explode(',',$data['school_type']));
						$dataTy = [];
						foreach ($school_type as $val) {
							 $dataTy[] = ['type_id' => $val, 'school_id' => $obj->id];
						}
						Db::name('school_type_data')->insertAll($dataTy);
					}
					if(!empty($data['school_xingzhi'])){
						$school_xingzhi = array_filter(explode(',',$data['school_xingzhi']));
						$dataXz = [];
						foreach ($school_xingzhi as $val) {
							 $dataXz[] = ['xingzhi_id' => $val, 'school_id' => $obj->id];
						}
						Db::name('school_xingzhi_data')->insertAll($dataXz);
					}*/
					Db::commit();
                    $this->success('添加成功');
                } else {
					Db::rollback();
                    $this->error('添加失败');
                }
            }
			
        } else {
            $id = $this->request->param('id', 0, 'intval');
			$sheng_list = Db::name('area')->where('level',1)->field('id,name')->where('pid',0)->select();
			$type_list = Db::name('school_type')->field('id,title')->select();
			$tese_list = Db::name('school_tese')->field('id,title')->select();
			$xingzhi_list = Db::name('school_xingzhi')->field('id,title')->select();
			$suoshu_list = SchoolModel::getSuoshuList();
			$xingzhi_list2 = SchoolModel::getXingzhiList2();
            if ($id) {
                $list = SchoolModel::where('id', '=', $id)->find();
				$city_list = Db::name('area')->field('id,name')->where('level',2)->where('pid',$list['province_id'])->select();
				$xian_list = Db::name('area')->field('id,name')->where('level',3)->where('pid',$list['city_id'])->select();
            }else{
				$list = $city_list = $xian_list = [];
				$list['img_fengcai'] = '';
				$list['syiliu'] = '';
				$list['syiliu_count'] = 0;
				$list['pinggu'] = '';
				$list['pinggu_count'] = 0;
				$list['tese_major'] = '';
				$list['tese_major_count'] = 0;
            }
			
			//$list['school_type'] = Db::name('school_type_data')->where('school_id',$id)->column('type_id');
			$list['school_tese'] = Db::name('school_tese_data')->where('school_id',$id)->column('tese_id');
			//$list['school_xingzhi'] = Db::name('school_xingzhi_data')->where('school_id',$id)->column('xingzhi_id');
			
			$img_fengcai = explode(',',$list['img_fengcai']);
			$img_fengcai = array_filter($img_fengcai);
			$this->assign('img_fengcai', $img_fengcai);
			$list['img_fengcai'] = implode(',',$img_fengcai);
			$img_fengcai_js = json_encode($img_fengcai);
			$this->assign('img_fengcai_js', $img_fengcai_js);
		
			$list['syiliu'] = json_decode($list['syiliu'],true);
			$list['syiliu_count'] = $list['syiliu']?count($list['syiliu']):0;
			$list['pinggu'] = json_decode($list['pinggu'],true);
			$list['pinggu_count'] = $list['pinggu']?count($list['pinggu']):0;//dump($list['pinggu']);
			$list['tese_major'] = json_decode($list['tese_major'],true);
			$list['tese_major_count'] = $list['tese_major']?count($list['tese_major']):0;
			//$major_list = Db::name('major')->field('id,cate_title')->where('cate_level',3)->select();
            return $this->fetch('',['list'=>$list,'sheng_list'=>$sheng_list,'city_list'=>$city_list,'xian_list'=>$xian_list,'type_list'=>$type_list,'tese_list'=>$tese_list,'xingzhi_list'=>$xingzhi_list,'suoshu_list'=>$suoshu_list,'xingzhi_list2'=>$xingzhi_list2]);
        } 
        
    }
	
	
    public function edit_yuanxi(){
       if ($this->request->isPost()) {
            $data = $this->request->post();//dump($data);die;
			
			if(empty($data['id'])){
				$this->error('非法访问');
			}
			
			if(empty($data['yuanxi'])){
				$this->error('请填写数据');
			}
			/*$dataY = [];
			foreach($data['yuanxi'] as $k=>$v){
				$dataY[$k] = ['school_id'=>$data['id'],'title'=>$v['title'],'major_ids'=>implode(',',$v['major_ids'])];
			}
			if(!empty($dataY)){
				Db::name('school_major_data')->where('school_id',$data['id'])->delete();
				Db::name('school_major_data')->insertAll($dataY);
				$this->success('编辑成功');
			}else{
				$this->error('请填写数据');
			}*/
			$yuanxi = json_encode(array_values($data['yuanxi']),JSON_UNESCAPED_UNICODE);
			$res = Db::name('school')->where('id',$data['id'])->update(['yuanxi'=>$yuanxi]);
			if ($res!== false) {
				$this->success('编辑成功');
			}else{
				$this->success('编辑失败');
			}
			
        } else {
            $id = $this->request->param('id', 0, 'intval');
            if ($id) {
                $list = SchoolModel::where('id', '=', $id)->field('id,college_name,yuanxi')->find();
            }else{
				$this->error('非法访问');
            }
			//$major_list = Db::name('major')->field('id,cate_title')->where('cate_level',3)->select();
			//$yuanxi_list = Db::name('school_major_data')->where('school_id',$id)->select();
				
			$yuanxi_list = json_decode($list['yuanxi'],true);;
			$yuanxi_count = !empty($yuanxi_list)?count($yuanxi_list):0;
            return $this->fetch('',['list'=>$list,'yuanxi_list'=>$yuanxi_list,'yuanxi_count'=>$yuanxi_count]);
        } 
        
    }
	public function edit_jiekou(){
       if ($this->request->isPost()) {
            $data = $this->request->post();
			$validate = validate('School');
			if (!$validate->check($data)) {
				$this->error($validate->getError());
			}
			$this->error('非法访问');
			if ($data['id']) {//编辑
                $res = SchoolModel::update($data, ['id' => $data['id']]);
                if ($res) {
                    $this->success('编辑成功');
                } else {
                    $this->error('编辑失败');
                }
            } else {//添加
                $this->error('非法访问');
            }
        } else {
            $id = $this->request->param('id', 0, 'intval');
            if ($id) {
                $list = SchoolModel::where('id', '=', $id)->find();
            }else{
				$list = [];
            }
            return $this->fetch('',['list'=>$list]);
        } 
        
    }
    public function del(){
        $id = $this->request->param('id', 0, 'intval');
        if ($id) {
			$res = SchoolModel::where('id',$id)->delete();
			if ($res) {
				$this->success('删除成功');
			}else {
				$this->error('删除失败');
			}
        } else {
            $this->error('参数错误');
        }
        
    }
    
    public function import(){
		
        if ($this->request->isPost()) {
			set_time_limit(0); 
            $data = $this->request->post();
            if(empty($data['file_url'])){
                $this->error('请上传文件');
            }
            $config   = ['path' => '.'.dirname($data['file_url'])];
            $excel  = new \Vtiful\Kernel\Excel($config);
            $data = $excel->openFile(basename($data['file_url']))->openSheet()->getSheetData();
            if(empty($data)){
                $this->error('文件没有内容');
            }
            if(count($data)<2){
                $this->error('文件没有内容');
            }
            unset($data[0]);//dump(count($data));die;
            $array = [];
			$tese_arr_all = $yuanxi_all = $zhaosheng_all = $baogao_all = [];//需要单独处理
			$school_suoshu_arr = ['教育部'=>1,'中科院'=>2,'省政府'=>3,'省教育厅'=>4,'自治区政府'=>5,'自治区教育厅'=>6,'中央办公厅'=>7,'市政府'=>8];
			$nowtime = time();
			$type_ids = Db::name('school_type')->column('title_fu,id');
            foreach($data as $k=>$v){
				if(empty($v[0])){
					$this->error('第'.($k+1).'行id为空');
				}
				if(!empty($v[3])){
					if(!empty($type_ids[$v[3]])){
						$school_type = $type_ids[$v[3]];
					}else{
$this->error('第'.($k+1).'行院校类型:'.$v[3].'不存在');
					}
				}else{
$this->error('第'.($k+1).'行行院校类型未填写');
				}
				
				$tese_arr = explode(',',$v[4]);
				$tese_arr = array_filter($tese_arr);
				if(!empty($tese_arr)){
					$tese_arr_all[$v[0]] = $tese_arr;
				}
				if($v[5] == '公办'){
					$school_xingzhi = 1;
				}elseif($v[5] == '民办'){
					$school_xingzhi = 2;
				}else{
					$school_xingzhi = 3;
				}
				if($v[6] == '普通本科' || $v[6] == '本科'){
					$school_xingzhi2 = 1;
				}else{
					$school_xingzhi2 = 2;
				}
				$v[7] = trim($v[7]);
				if(!empty($v[7])){
					if(!empty($school_suoshu_arr[$v[7]]) ){
						$school_suoshu = $school_suoshu_arr[$v[7]];
					}else{
						$this->error('第'.($k+1).'行院校所属不存在');
					}
				}else{
$this->error('第'.($k+1).'行院校所属未填写');
				}
				
				if(!empty($v[18])){
					$result = json_decode($v[18]);
					if (json_last_error() !== JSON_ERROR_NONE) {
						$this->error('第'.($k+1).'行评估数据格式错误');
					} 
				}
				if(!empty($v[19])){
					$result = json_decode($v[19]);
					if (json_last_error() !== JSON_ERROR_NONE) {
						$this->error('第'.($k+1).'行特色专业数据格式错误');
					} 
				}
				
				if(!empty($v[20])){
					$result = json_decode($v[20]);
					if (json_last_error() !== JSON_ERROR_NONE) {
						$this->error('第'.($k+1).'行院校设置数据格式错误');
					}else{
						$yuanxi_all[$v[0]] = json_decode($v[20],true);
					} 
				}
				if(!empty($v[21])){
					$result = json_decode($v[21]);
					if (json_last_error() !== JSON_ERROR_NONE) {
						$this->error('第'.($k+1).'行招生简章数据格式错误');
					}else{
						$zhaosheng_all[$v[0]] = json_decode($v[21],true);
					}  
				}
				if(!empty($v[22])){
					$result = json_decode($v[22]);
					if (json_last_error() !== JSON_ERROR_NONE) {
						$this->error('第'.($k+1).'行就业报告数据格式错误');
					}else{
						$baogao_all[$v[0]] = json_decode($v[22],true);
					}  
				}
				
                $array[$k] = ['id'=>$v[0],'college_code'=>$v[2],'school_type'=>$school_type??'1','school_xingzhi'=>$school_xingzhi,'school_xingzhi2'=>$school_xingzhi2,'school_suoshu'=>$school_suoshu??'','hot_nums'=>$v[8],'difficult_nums'=>$v[9],'ranking'=>$v[10],'year'=>$v[11],'shuoshi_count'=>$v[12],'boshi_count'=>$v[13],'intro'=>$v[4],'address'=>$v[15],'call_number'=>$v[16],'web_site'=>$v[17],'pinggu'=>$v[18],'tese_major'=>$v[19],'yuanxi'=>$v[20],'update_time'=>$nowtime];//'shizi'=>$v[15],
            }
			try{
				//Db::startTrans();
				if(isset($array) && !empty($array)) {
	$obj = new SchoolModel();
					//$obj = new SchoolTest();
					$obj->saveAll($array);
				}else{
					$this->error('没有数据可以导入');
				}
				$ids = array_column($array,'id');
				
				//特色处理
				Db::name('school_tese_data')->where('school_id','in',$ids)->delete();
				if(isset($tese_arr_all) && !empty($tese_arr_all)) {
					$tese_ids = Db::name('school_tese')->column('title,id');
					$dataTs = [];
					foreach($tese_arr_all as $k=>$v){
						foreach ($v as $val) {
							if(!empty($tese_ids[$val])){
								$dataTs[] = ['tese_id' => $tese_ids[$val], 'school_id' => $k];
							}
						}
					}
					if(!empty($dataTs)){
						Db::name('school_tese_data')->insertAll($dataTs);
					}
				}
				//院系处理  改成json的形式直接存主表里了
				/*Db::name('school_major_data')->where('id','>',0)->delete();
				if(isset($yuanxi_all) && !empty($yuanxi_all)) {
					$dataY = [];
					foreach($yuanxi_all as $k=>$v){
						foreach($v as $k1=>$v1){
							$dataY[] = ['school_id'=>$k,'title'=>$v1['title'],'major_ids'=>implode(',',$v1['major_ids']),'create_time'=>$nowtime];
						}
					}
					if(!empty($dataY)){
						Db::name('school_major_data')->insertAll($dataY);
					}
				}*/
				
				//招生简章处理
				Db::name('school_article')->where('school_id','in',$ids)->delete();
				if(isset($zhaosheng_all) && !empty($zhaosheng_all)) {
					$dataZ = [];
					foreach($zhaosheng_all as $k=>$v){
						foreach($v as $k1=>$v1){
							$dataZ[] = ['school_id'=>$k,'type'=>1,'title'=>$v1['title'],'writer'=>$v1['writer'],'views'=>$v1['views'],'content'=>$v1['content'],'create_time'=>$nowtime];
						}
					}
					if(!empty($dataZ)){
						Db::name('school_article')->insertAll($dataZ);
					}
				}
				//就业报告处理
				if(isset($baogao_all) && !empty($baogao_all)) {
					$dataB = [];
					foreach($baogao_all as $k=>$v){
						foreach($v as $k1=>$v1){
							$dataB[] = ['school_id'=>$k,'type'=>2,'content_type'=>$v1['content_type'],'title'=>$v1['title'],'views'=>$v1['views'],'file_url'=>!empty($v1['file_url'])?$v1['file_url']:'','content'=>!empty($v1['content'])?$v1['content']:'','create_time'=>$nowtime];
						}
					}
					if(!empty($dataB)){
						Db::name('school_article')->insertAll($dataB);
					}
				}
				
			}catch (\Exception $e) {
				//Db::rollback();
				$this->error($e->getMessage());
			}
			//Db::commit();
			$this->success('导入成功');
        } else {
            return $this->fetch();
        }
    }

}




?>